package model;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.Writer;
import java.nio.charset.Charset;

public class EncrypterTransformation implements Encrypter {

	public EncrypterTransformation() {

	}

	/* (non-Javadoc)
	 * @see model.Encrypter#encrypt(java.io.InputStream, java.io.OutputStream)
	 */
	public void encrypt(InputStream stream, OutputStream out) throws IOException {
		Charset utf8 = Charset.forName("UTF-8");
		Reader r = new InputStreamReader(stream, utf8);
		Writer w = new OutputStreamWriter(out, utf8);
		
		
		
		int sign = r.read();
		for (int i = 0; sign >= 0; i++) {
			w.write(sign + 50);
			sign = r.read();
			if (i % 50 == 0) {
				w.flush();
			}
		}
		w.flush();
	}

	/* (non-Javadoc)
	 * @see model.Encrypter#decrypt(java.io.InputStream, java.io.OutputStream)
	 */
	public void decrypt(InputStream stream, OutputStream out) throws IOException {
		Charset utf8 = Charset.forName("UTF-8");
		Reader r = new InputStreamReader(stream, utf8);
		Writer w = new OutputStreamWriter(out, utf8);
		int sign = r.read();
		for (int i = 0; sign >= 0; i++) {
			if (sign < 50) {
				throw new IllegalArgumentException("Character '" + Integer.toString(sign) + "' was not encryptet before - please encrypt before you decrypt.");
			}
			w.write(sign - 50);
			sign = r.read();
			if (i % 50 == 0) {
				w.flush();
			}
		}
		w.flush();
	}
//	
//	public String decrypt(String toCompile) {
//		ByteArrayInputStream bais = new ByteArrayInputStream(toCompile.getBytes());
//		StringBuilder sb = new StringBuilder();
//		int sign = bais.read();
//		while(sign >= 0) {
//			sb.append(new Character(Integer.))
//		}
//		
//		return toCompile;
//		
//	}

}
